package com.jfinal.aceadmin.model;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Repository;

import com.jfinal.aceadmin.util.JsonUtil;
import com.jfinal.aceadmin.util.StringUtil;
import com.jfinal.aceadmin.util.VoUtil;
import com.jfinal.aceadmin.vo.AttachmentVo;
import com.jfinal.aceadmin.vo.EmailAttachmentVo;
import com.jfinal.aceadmin.vo.EmailDetailVo;
import com.jfinal.aceadmin.vo.EmailSimpleVo;
import com.jfinal.aceadmin.vo.InboxVo;
import com.jfinal.plugin.activerecord.Page;

@Repository
public class EmailImpl {
	private static ApplicationContext ctx;

	public static EmailImpl getDAO() {
		if (null == ctx) {
			ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
		}
		EmailImpl instance = ctx.getBean(EmailImpl.class);
		return instance;
	}

	public InboxVo getUserEmails(int userId) {
		InboxVo inboxVo = new InboxVo();
		int unreadEmails = Email.dao.countByUserIdAndRead(userId, false);
		Page<EmailSimpleVo> pageResult = findEmailByPage(userId);
		inboxVo.setPageResult(pageResult);
		inboxVo.setUnreadEmails(unreadEmails);
		return inboxVo;
	}

	public Page<EmailSimpleVo> findEmailByPage(int userId) {
		Page<Email> page = Email.dao.paginate(1, 10, "SELECT * ",
				"FROM Email WHERE userId = ?", userId);
		List<Email> emails = page.getList();
		List<EmailSimpleVo> emailVos = new ArrayList<EmailSimpleVo>();
		for (Email email : emails) {
			EmailSimpleVo emailVo = VoUtil.convert(email);
			emailVos.add(emailVo);
		}

		Page<EmailSimpleVo> result = new Page<EmailSimpleVo>(emailVos,
				page.getPageNumber(), page.getPageSize(), page.getTotalPage(),
				page.getTotalRow());
		return result;
	}

	public EmailDetailVo getEmailDetailVoByEmailId(long emailId) {
		Email email = Email.dao.findById(emailId);
		EmailSimpleVo emailSimpleVo = VoUtil.convert(email);
		EmailDetailVo emailDetailVo = new EmailDetailVo();
		emailDetailVo.setContent(email.getContent());
		emailDetailVo.setEmailSimpleVo(emailSimpleVo);
		EmailAttachmentVo emailAttachmentVo = new EmailAttachmentVo();
		long totalSize = 0;
		List<AttachmentVo> attachmentVos = new ArrayList<AttachmentVo>();
		List<EmailAttachment> attachments = EmailAttachment.dao
				.findByEmailId(email.getBaseId());
		for (EmailAttachment attachment : attachments) {
			AttachmentVo attachmentVo = VoUtil.convert(attachment);
			attachmentVos.add(attachmentVo);
			totalSize += attachmentVo.getFileSize();
		}
		emailAttachmentVo.setAttachments(attachmentVos.size());
		emailAttachmentVo.setTotalSize(StringUtil.getFormatSize(totalSize));
		emailAttachmentVo.setAttachmentVos(attachmentVos);
		emailDetailVo.setEmailAttachmentVo(emailAttachmentVo);
		return emailDetailVo;
	}

	public boolean markEmailAsReaded(long emailId) {
		Email email = Email.dao.findById(emailId);
		if (null != email) {
			email.setReaded(true);
			email.update();
			return true;
		}
		return false;
	}

	public void saveEmail(String recipient, String subject, String message,
			String attachementFiles, String name) {
		User user = User.dao.findByName(name);
		if (null != user) {
			User sender = User.dao.findByEmail(recipient);
			if (null != sender) {
				Email email = new Email();
				email.setUserId(sender.getId());
				email.setSenderId(user.getId());
				email.setSubject(subject);
				email.setContent(message);
				email.setCreatedDate(new Date());
				email.setSenderName(user.getName());
				email.setReaded(false);
				email.setFlaged(false);
				email.save();
				long emailId = email.getBaseId();
				List<AttachmentVo> attachements = JsonUtil
						.parseObjectByJsonString(attachementFiles,
								AttachmentVo.class);
				for (AttachmentVo attachment : attachements) {
					EmailAttachment emailAttachment = new EmailAttachment();
					emailAttachment.setEmailId(emailId);
					emailAttachment.setCreatedDate(new Date());
					emailAttachment.setFileName(attachment.getFileName());
					emailAttachment.setFileSize(attachment.getFileSize());
					emailAttachment.setFilePath(attachment.getFileName());
					emailAttachment.save();
				}
				UserMessageImpl.getDAO().sendMessage(email);
			}

		}

	}

	public boolean flagEmail(long emailId) {
		Email email = Email.dao.findById(emailId);
		if (null != email) {
			if (email.getFlaged()) {
				email.setFlaged(false);
			} else {
				email.setFlaged(true);
			}
			email.update();
			return true;
		}
		return false;
	}
}